package org.grow.yc.filter;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.grow.yc.entity.dto.AjaxResult;
import org.springframework.core.MethodParameter;
import org.springframework.core.annotation.Order;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * @Author: xwg
 * @CreateDate: 2024/10/14
 */

//@RestControllerAdvice
//    todo:以后解决

//作用范围 不包括静态资源请求，作用在 @RestController 和 返回值 是 ResponseEntity 的方法上
public class ResponseBodyFormatter implements ResponseBodyAdvice {

    private ObjectMapper objectMapper = new ObjectMapper();

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        System.out.println("body ========= " + body + body.getClass().getName());
        if (body instanceof String) {
//            无法区分普通返回string 与 异常string body自动解包？？
//            System.out.println(returnType.getMethodAnnotations());
//            System.out.println(returnType.getMethodAnnotation(ExceptionHandler.class));
            System.out.println("true body ========= "+body);
            AjaxResult<Object> build = AjaxResult.builder().code(20000).message("success").data(body).build();
            try {
                return objectMapper.writeValueAsString(build);
            } catch (JsonProcessingException e) {
                return body;
            }
        } else if (body instanceof ResponseEntity) {
            ResponseEntity r = (ResponseEntity) body;
            System.out.println("-------" + r);
//            异常
            return AjaxResult.builder().code(r.getStatusCode().value()).message(r.getBody().toString()).build();
        } else {
            return AjaxResult.builder().code(20000).message("success").data(body).build();
        }
//        return null;
//        return body;

    }
}
